package com.chatplus.application.controller.admin.biz;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.chatplus.application.common.exception.BadRequestException;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.config.pay.PayConfig;
import com.chatplus.application.domain.entity.basedata.ConfigEntity;
import com.chatplus.application.domain.request.admin.ConfigUpdateAdminApiRequest;
import com.chatplus.application.domain.response.FileDetailApiResponse;
import com.chatplus.application.service.basedata.ConfigService;
import com.chatplus.application.service.file.FileService;
import com.chatplus.application.web.basecontroller.BaseController;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;

import static cn.dev33.satoken.stp.StpUtil.isLogin;

/**
 * 系统配置
 */
@Validated
@RestController
@RequestMapping("/api/admin/config")
@Tag(name = "配置API", description = "配置API")
public class ConfigAdminApiController extends BaseController {
    static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(ConfigAdminApiController.class);
    private final ConfigService configService;
    private final ObjectMapper objectMapper;
    private final PayConfig.Properties properties;

    public ConfigAdminApiController(ConfigService configService, ObjectMapper objectMapper, PayConfig.Properties properties) {
        this.configService = configService;
        this.objectMapper = objectMapper;
        this.properties = properties;
    }

    @GetMapping("get")
    @Operation(summary = "获取后台配置")
    public Object get(@RequestParam(value = "key") String key) {
        // 登录判断,除了系统配置，其他配置需要登录
        if (!key.equals("system") && !isLogin()) {
            throw new BadRequestException("未登录");
        }
        return switch (key) {
            case "system" -> configService.getSystemConfig();
            case "notice" -> configService.getNoticeConfig();
            case "file" -> configService.getFileConfig();
            case "extend" -> configService.getExtendConfig();
            case "devops" -> configService.getDevopsConfig();
            default -> null;
        };
    }

    @PostMapping("update")
    @Operation(summary = "更新后台配置")
    public Object update(@RequestBody ConfigUpdateAdminApiRequest request) {
        String key = request.getKey();
        try {
            ConfigEntity configEntity = configService.getByMarker(key);
            if (configEntity == null) {
                configEntity = new ConfigEntity();
            }
            configEntity.setConfig(objectMapper.writeValueAsString(request.getConfig()));
            configEntity.setMarker(key);
            configService.saveOrUpdate(configEntity);
        } catch (Exception e) {
            LOGGER.message("更新后台配置失败").exception(e).error();
            throw new BadRequestException("更新后台配置失败");
        } finally {
            configService.init();
        }
        return get(key);
    }

    /**
     * 上传接口
     */
    @PostMapping("/uploadCert")
    public FileDetailApiResponse uploadCert(@RequestParam("file") MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            assert fileName != null;
            String fileSuffix = StringUtils.substring(fileName, fileName.lastIndexOf("."), fileName.length());
            // 指定文件存储路径，这里存储在当前目录下
            String filePath = getPath(fileSuffix);
            // 将文件保存到指定路径
            file.transferTo(new File(filePath));
            FileDetailApiResponse response = new FileDetailApiResponse();
            response.setUrl(filePath);
            return response;
        } catch (Exception e) {
            LOGGER.message("上传文件失败").exception(e).error();
            throw new BadRequestException("上传文件失败");
        }
    }

    public String getPath(String suffix) {
        // 生成uuid
        String uuid = IdUtil.fastSimpleUUID();
        String folder = properties.getCertFolder();
        if (StringUtils.isBlank(folder)) {
            LOGGER.message("证书文件夹未配置").error();
            throw new BadRequestException("证书文件夹未配置-请在应用中进行配置");
        }
        // 文件路径
        String path = folder + FileService.FILE_SEPARATOR + DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        // 判断文件夹是否存在，不存在则创建文件夹
        File file = new File(path);
        if (!file.exists()) {
            boolean wasSuccessful = file.mkdirs();
            if (!wasSuccessful) {
                LOGGER.message("文件夹创建失败").context("path", path).error();
                throw new BadRequestException("文件夹创建失败");
            }
        }
        return path + FileService.FILE_SEPARATOR + uuid + suffix;
    }

}
